﻿#include <iostream>
using namespace std;
//引用：给变量起别名
//语法：数据类型 &别名 = 原名
//引用必须初始化
//引用一旦初始化，不可再更改
//引用的本质:指针常量
//int& ref = a;自动转换为int* const ref = &a;
/*
指针常量:指向不可改,值可改
常量指针:指向可以改,值不可以改
*/

//常量引用:在函数列表中,修饰形参,防止误操作
//打印数据函数
void showValue(const int & val)//加入const防止误操作
{
	//val = 1000;
	cout << "val = " << val << endl;
}
int main()
{	
	//使用场景:在函数列表中修饰形参,防止误操作	

	//加上const之后,编译器将代码修改为 int temp = 10;const int& ref = temp;
	//const int& ref = 10;//引用必须引用一块合法的内存空间
	//ref = 20;//加入const之后变为只读,不可修改

	int a = 100;
	showValue(a);
	cout << "a = " << a << endl;

	system("pause");
	return 0;
}

/*
//引用做函数返回值
//1\注意不要返回局部变量引用
int& test01()
{
	int a = 10;//局部变量存在栈区
	return a;
}
//2\函数调用作为左值
int& test02()
{
	static int a = 10;//静态变量在全局区,程序结束后系统释放
	return a;
}

int main()
{
	int& ref = test01();

	cout << "ref = " << ref << endl;
	cout << "ref = " << ref << endl;

	int& ref2 = test02();

	cout << "ref2 = " << ref2 << endl;
	cout << "ref2 = " << ref2 << endl;
	//2\函数调用作为左值
	test02() = 1000;

	cout << "ref2 = " << ref2 << endl;
	cout << "ref2 = " << ref2 << endl;

	system("pause");
	return 0;
}
*/

/*
//引用做函数参数
//作用：利用引用让形参修饰实参，简化指针修改实参
//交换函数
//1、值传递
void mySwap01(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;

	//cout << "Swap01 a = " << a << endl;
	//cout << "Swap01 b = " << b << endl;
}

//2、地址传递
void mySwap02(int *a, int *b)
{
	int temp = *a;
	*a = *b;
	*b = temp;

	//cout << "Swap02 a = " << a << endl;
	//cout << "Swap02 b = " << b << endl;
}

//3\引用传递
void mySwap03(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;

	//cout << "Swap03 a = " << a << endl;
	//cout << "Swap03 b = " << b << endl;
}

int main()
{
	int a = 10;
	int b = 20;

	//mySwap01(a, b);//值传递，形参不修饰实参
	//mySwap02(&a, &b);//地址传递，形参会修饰实参
	mySwap03(a, b);//引用传递，形参会修饰实参

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	system("pause");
	return 0;
}
*/

/*
//引用基础使用
int main()
{

	int a = 10;
	int& b = a;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	b = 100;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	system("pause");
	return 0;
}
*/